package org.finesys.system.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.finesys.common.core.exception.ErrorCodes;
import org.finesys.common.core.module.R;
import org.finesys.common.core.util.MessageUtil;
import org.finesys.common.excel.exception.ErrorMessage;
import org.finesys.common.mp.core.service.impl.BaseServiceImpl;
import org.finesys.system.api.entity.SysPost;
import org.finesys.system.api.vo.PostExcelVO;
import org.finesys.system.convert.SysPostConvert;
import org.finesys.system.mapper.SysPostMapper;
import org.finesys.system.service.SysPostService;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.hutool.core.collection.CollUtil;

@Service
public class SysPostServiceImpl extends BaseServiceImpl<SysPostMapper, SysPost> implements SysPostService {


    @Override
    public R<?> importExcel(List<PostExcelVO> excelVOList, BindingResult bindingResult) {

        // 通用校验获取失败的数据
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

        // 个性化校验逻辑
        List<SysPost> postList = this.list();

        // 执行数据插入操作 组装 PostDto
        for (PostExcelVO excel : excelVOList) {
            Set<String> errorMsg = new HashSet<>();
            // 检验岗位名称或者岗位编码是否存在
            boolean existPost = postList.stream()
                    .anyMatch(post -> excel.getPostName().equals(post.getPostName())
                            || excel.getPostCode().equals(post.getPostCode()));

            if (existPost) {
                errorMsg.add(MessageUtil.getMessage(ErrorCodes.SYS_POST_NAMEORCODE_EXISTING, excel.getPostName(),
                        excel.getPostCode()));
            }

            // 数据合法情况
            if (CollUtil.isEmpty(errorMsg)) {
                insertExcelPost(excel);
            } else {
                // 数据不合法
                errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
            }
        }
        if (CollUtil.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        }
        return R.success();
    }

    private void insertExcelPost(PostExcelVO excel) {
        SysPost sysPost = SysPostConvert.INSTANCE.convert(excel);
        this.save(sysPost);
    }

    @Override
    public List<PostExcelVO> listPost() {
        List<SysPost> sysPosts = baseMapper.selectList(Wrappers.emptyWrapper());
        return SysPostConvert.INSTANCE.convertList(sysPosts);
    }
}
